<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\DB;

class User extends Authenticatable
{
    use Notifiable;

    protected $abilities;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'shop_id',
        'name',
        'email',
        'password',
        'nickname',
        'avatar_url',
        'sex',
        'parent_id',
        'phone',
        'service_message',
        'openid',
        'xcx_openid',
        'unionid',
        'city',
        'options',
        'json',
        'session_id',
        'integral',
        'in_blacklist',
        'is_distribution_statistics'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function carts()
    {
        return $this->hasMany('App\Models\Cart');
    }
    public function orders()
    {
        return $this->hasMany('App\Models\Order');
    }

    public function bonuses()
    {
        return $this->hasMany('App\Models\Bonus');
    }

    public function parent()
    {
        return $this->belongsTo('App\User','parent_id');
    }
    public function juniors()
    {
        return $this->hasMany('App\User','parent_id');
    }

    public function addresses()
    {
        return $this->hasMany('App\Models\Address');
    }

    public function roles()
    {
        return $this->belongsToMany('App\Models\Role');
    }

    public function initAbilities()
    {
        $role_ids = $this->roles()->pluck('role_id')->toArray();
        $ability_ids = DB::table('ability_role')->whereIn('role_id', $role_ids)->pluck('ability_id');
        $this->abilities = \App\Models\Ability::whereIn('id', $ability_ids)->get()->keyBy('name');
    }

    public function checkAbility($name)
    {
        if(!$this->abilities)
            $this->initAbilities();
        return $this->abilities->get($name, false);
    }

    public function checkRole($name)
    {
        $roles = $this->roles->keyBy('name');
        return $roles->get($name, false);
    }

    public function roleIds()
    {
        return $this->roles()->pluck('role_id')->toArray();
    }
}
